<?php

class Bankwire extends Page_Controller {
    private static $allowed_actions = array(
        'process',
        'RegisterBankReferenceForm',
        'register_bank_reference'
    );

    function process() {
        if(SecurityToken::inst()->checkRequest($this->request)){
        	try {
            	DB::getConn()->transactionStart();
            	$payment = BankPayment::get()->byID($this->request->param('ID'))->pendingPayment();
				DB::getConn()->transactionEnd();
            	return $this->redirect($payment->RedirectLink());
			}
            catch(ValidationException $e) {
                DB::getConn()->transactionRollback();
                SS_Log::log(new Exception(print_r($e->getMessage(), true)), SS_Log::NOTICE);
				$this->setMessage('error', $e->getResult()->message());
				return $this->redirectBack();
            }
        }
        
        return $this->httpError('404');
    }
    
    function RegisterBankReferenceForm() {
        $fields = FieldList::create(
            HiddenField::create('ID', 'ID'),
            $bank_name = ReadonlyField::create('BankName', _t('Bankwire.BANK_NAME', 'Bank Name')),
            $bank_branch = ReadonlyField::create('BankBranch', _t('Bankwire.BANK_BRANCH', 'Bank Branch')),
            $account_name = ReadonlyField::create('AccountName', _t('Bankwire.ACCOUNT_NAME', 'Account Name')),
            $account_number = ReadonlyField::create('AccountNumber', _t('Bankwire.ACCOUNT_NUMBER', 'Account No.')),
            TextField::create('TransactionID', _t('Bankwire.TRANSACTION_ID', 'Transaction ID')),
            $date_field = DateField::create('TransactionDate', _t('Bankwire.TRANSACTION_DATE', 'Transaction Date')),
            $time_field = TimeField::create('TransactionTime', _t('Bankwire.TRANSACTION_TIME', 'Transaction Time'))
        );
        
        $bank_name->setIncludeHiddenField(true);
        $bank_branch->setIncludeHiddenField(true);
        $account_name->setIncludeHiddenField(true);
        $account_number->setIncludeHiddenField(true);
		
		$date_field->setDescription(sprintf(
			_t('Bankwire.Example', 'e.g. %s', 'Example format'),
			Convert::raw2xml(Zend_Date::now()->toString($date_field->getConfig('dateformat')))
		));
		
		$time_field->setDescription(sprintf(
			_t('Bankwire.Example', 'e.g. %s', 'Example format'),
			Convert::raw2xml(Zend_Date::now()->toString($time_field->getConfig('timeformat')))
		));
        
        $actions = FieldList::create(FormAction::create("doRegister", _t('Bankwire.BUTTONREGISTER', 'Register Bank Reference')));

        $validator = RequiredFields::create('TransactionID', 'TransactionDate', 'TransactionTime');

        return Form::create($this, 'RegisterBankReferenceForm', $fields, $actions, $validator);
    }

    function doRegister($data, $form) {
        try {
        	DB::getConn()->transactionStart();
            $payment = BankPayment::get()->byID((int)$data['ID']);
            if($payment && $payment->Status == 'Pending') {
                $form->saveInto($payment);
                $payment->processPayment();
            }
			DB::getConn()->transactionEnd();
            return _t('Bankwire.SUCCESS_REGISTERED_BANK_REFERENCE', 'You\'ve been registered your bank reference successfully');
        }
        catch(ValidationException $e) {
        	DB::getConn()->transactionRollback();
            SS_Log::log(new Exception(print_r($e->getMessage(), true)), SS_Log::NOTICE);
            $form->sessionMessage($e->getResult()->message(), 'error');
        }
        
        $token = SecurityToken::inst();
        $link = $token->addToUrl(Controller::join_links('bankwire', 'register_bank_reference', $data['ID']));
        return $this->redirect($link);
    }

    function register_bank_reference() {
        if($this->request->isAjax() && SecurityToken::inst()->checkRequest($this->request)){
            $payment = BankPayment::get()->byID((int)$this->request->param('ID'));
            if($payment){
                if($payment->Status == 'Pending') {
                    return $this->RegisterBankReferenceForm()->loadDataFrom($payment)->forTemplate();
                }
                else{
                    return _t('Bankwire.SUCCESS_REGISTERED_BANK_REFERENCE', 'You\'ve been registered your bank reference successfully');
                }
            }
        }

        return $this->httpError('404');
    }
}
